<?php
namespace App\Http\Controllers\Admin;
class Common
{
	public function getTree($pInfo, $spread = true){
	    $res = [];
	    $tree = [];
	    //整理数组
	    foreach($pInfo as $key=>$vo){
	        if($spread){
	            $vo['spread'] = true;  //默认展开
	        }
	        $res[$vo['id']] = $vo;
	        $res[$vo['id']]['children'] = [];
	    }
	    unset($pInfo);
	    //查找子孙
	    foreach($res as $key=>$vo){
	        if(0 != $vo['pid']){
	            $res[$vo['pid']]['children'][] = &$res[$key];
	        }
	    }
	    //过滤杂质
	    foreach( $res as $key=>$vo ){
	        if(0 == $vo['pid']){
	            $tree[] = $vo;
	        }
	    }
	    unset( $res );
	    return $tree;
	}

	// 三维数组转二维数组
    public static function Array_3dTo2d ($arr_3d){
        $arr_2d = [];
        foreach($arr_3d as $k => $v){
            foreach($arr_3d[$k] as $ke => $va){
                if(is_array($va)){
                    array_push($arr_2d,$va);
                }
            }
            if(!is_array($va)){
                array_push($arr_2d,$v);
            }
        }
        return $arr_2d;
    }

	/**
	 * [一维数组转树]
	 */
	public static function Arr2Tree($list, $id = 'id', $pid = 'pid', $son = 'children') {
        $tree = $map = array();
        foreach ($list as $item) {
            $map[$item[$id]] = $item;
        }
        foreach ($list as $item) {
            if (isset($item[$pid]) && isset($map[$item[$pid]])) {
                $map[$item[$pid]][$son][] = &$map[$item[$id]];
            } else {
                $tree[] = &$map[$item[$id]];
            }
        }
        unset($map);
        return $tree;
    }
}
